package cn.codewen.filter;

import cn.codewen.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class CheckLoginFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {


//1. 转换成HttpServlet对象
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //2. 判断session
        //2.1 得到session Admin
        //Admin admin = (Admin) request.getSession().getAttribute("admin");
        User user = (User) request.getSession().getAttribute("user");
        System.out.println(user);
        //2.2 判断有没有session
        //2.2 接收参数
        String m = request.getParameter("m");


        //定义1个白名单统统放行

        Boolean isOk = false;

        String[] dirs = {"/css/", "/fonts/", "/js/","/reg.jsp"};

        String requestURI = request.getRequestURI();


        for (String dir : dirs) {

            if (requestURI.startsWith(dir)) {
                isOk = true;
            }
        }

        System.out.println("999999999999999");
        System.out.println(requestURI);
        System.out.println("999999999999999");

        //2.3判断有没有session
        if (user != null || (m != null && m.equals("login")) || isOk) {

            chain.doFilter(request, response);

        } else {

            response.sendRedirect("/user?m=login");
        }


    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
